package cn.com.cym.gamezao.advice;

import cn.com.cym.gamezao.base.ResultResponse;
import cn.com.cym.gamezao.exception.BaseException;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
public class ControllerAdvice {


    @ExceptionHandler(BaseException.class)
    public ResponseEntity<?> responseEntity(BaseException e){
        return ResponseEntity.badRequest().body(new ResultResponse(e.getResultResponse().getMessage(),e.getResultResponse().getStatus()));
        // return ResponseEntity.badRequest().body(new ResultResponse(e.getResultResponse().getMessage(),HttpStatus.FORBIDDEN.value()));
    }

    @ExceptionHandler(SQLException.class)
    public ResponseEntity<?> responseSQLIntegrityConstraintViolationException(SQLException e){

        if(e.getMessage().contains("a foreign key constraint fails")){
            return ResponseEntity.badRequest().body(new ResultResponse("关联子表数据未删除，无法删除父表数据", HttpStatus.INTERNAL_SERVER_ERROR.value()));
        }else if(e.getMessage().contains("Duplicate entry")){
            String[] split = e.getMessage().split("\'");
            if(split.length<2){
                return ResponseEntity.badRequest().body(new ResultResponse("未知错误，请联系系统管理员", HttpStatus.INTERNAL_SERVER_ERROR.value()));
            }
            return ResponseEntity.badRequest().body(new ResultResponse(split[1]+"--已存在不可重复", HttpStatus.INTERNAL_SERVER_ERROR.value()));
        }
        //System.out.println(e.getMessage());
        return ResponseEntity.badRequest().body(new ResultResponse(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.value()));
    }


    @ExceptionHandler(FileSizeLimitExceededException.class)
    public ResponseEntity<?> responseFileSizeLimitExceededException(FileSizeLimitExceededException e){
        return ResponseEntity.badRequest().body(new ResultResponse("上传文件过大，请控制文件大小在2M大小",HttpStatus.BAD_REQUEST.value()));
        // return ResponseEntity.badRequest().body(new ResultResponse(e.getResultResponse().getMessage(),HttpStatus.FORBIDDEN.value()));
    }
}
